package com.zhf.cloud.gateway.springcloudgateway.logback.mongodb;

import com.zhf.cloud.gateway.springcloudgateway.base.BaseResponse;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: 曾鸿发
 * @create: 2021-11-22 12:31
 * @description：
 **/
@Component
public class MongoDBRead {

    @Autowired
    private MongoTemplate mongoTemplate;

    public BaseResponse getlogs(int pageNum, int pageSize, String traceid,
                                String ip, String service,
                                String level, String message,
                                String errorinfo, String dtbeg, String dtend, String pid) {

        ////添加筛选条件
        Criteria qdate = new Criteria();

        qdate = setInfo(qdate, "traceid", traceid);
        qdate = setInfo(qdate, "ip", ip);
        qdate = setInfo(qdate, "service", service);
        qdate = setInfo(qdate, "level", level);
        qdate = setInfo(qdate, "message", message);
        qdate = setInfo(qdate, "errorinfo", errorinfo);
        qdate = setInfo(qdate, "pid", pid);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date endDate = null;
            if (dtend != null) {
                Calendar rightNow = Calendar.getInstance();
                var endday = format.parse(dtend);
                rightNow.setTime(endday);
                rightNow.add(Calendar.DAY_OF_YEAR, 1);
                endDate = rightNow.getTime();
            }
            if (dtbeg != null && dtend != null) {
                qdate = qdate.and("timestamp").gte(format.parse(dtbeg)).lte(endDate);
            } else if (dtbeg != null) {
                qdate = qdate.and("timestamp").gte(format.parse(dtbeg));
            } else if (dtend != null) {
                qdate = qdate.and("timestamp").lte(endDate);
            }
        } catch (Exception e) {
            System.out.print("SimpleDateFormat error :" + e.getMessage());
        }

        AggregationOperation match1 = Aggregation.match(qdate);

        Aggregation count_aggregate = Aggregation.newAggregation(
                match1,
                Aggregation.group().count().as("count")
        );

        Integer count = 10000;
        Iterator countMap = mongoTemplate.aggregate(count_aggregate, "log", Map.class).iterator();
        if(countMap != null && countMap.hasNext())
        {
            Map map1 = (Map)countMap.next();
            count = Integer.parseInt(map1.get("count").toString());
        }
//    Integer count = mongoTemplate.aggregate(count_aggregate, "log", Map.class).getMappedResults()
//        .size();

        //排序
        AggregationOperation sort = Aggregation.sort(Sort.Direction.DESC, "timestamp");
        //分页
        AggregationOperation skip = Aggregation.skip((pageNum - 1) * pageSize);
        AggregationOperation limit = Aggregation.limit(pageSize);

        Aggregation aggregate = Aggregation.newAggregation(match1, sort, skip, limit);

        List<Map> list = mongoTemplate.aggregate(aggregate, "log", Map.class).getMappedResults();
//    Iterator resultMap= mongoTemplate.aggregate(aggregate, "log", Map.class).iterator();
//    List<Map> list = Lists.newArrayList();
//    while (resultMap.hasNext())
//    {
//      list.add((Map)resultMap.next());
//    }
        BaseResponse response = new BaseResponse();
        response.totalCount = count;
        response.data = list;
        return response;
    }

    private Criteria setInfo(Criteria criteria, String paramName, String paramValue) {
        if (paramValue != null && !paramValue.isEmpty()) {
            return criteria.and(paramName).regex(paramValue);
        }
        return criteria;
    }
}